// 处理input和noisy_input文件夹中的图片
import fs from "fs";
import Router from "koa-router";
import { spawnSync } from "child_process";
import path from "path";

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const processRouter = new Router();

processRouter.prefix("/process");

processRouter.get("/input/:dataset", (ctx) => {
  const { dataset } = ctx.params;
  const sourcePath = path.join(
    process.cwd(),
    "app",
    "dataset",
    dataset,
    "images"
  );
  ctx.body = fs.readdirSync(sourcePath);
});

processRouter.get("/input/:dataset/:img", (ctx) => {
  const { dataset, img } = ctx.params;
  const filePath = path.join(
    process.cwd(),
    "app",
    "dataset",
    dataset,
    "images",
    img
  );
  let file = fs.readFileSync(filePath);
  ctx.set("content-type", "image/jpeg");
  ctx.set("cache-control", "no-store");
  ctx.body = file;
});

processRouter.get("/output", (ctx) => {
  const list = fs.readdirSync(path.join(process.cwd(), "app", "noisy_input"));
  ctx.body = list;
});

processRouter.get("/output/:img", (ctx) => {
  const { img } = ctx.params;
  const filePath = path.join(process.cwd(), "app", "noisy_input", img);
  let file = fs.readFileSync(filePath);
  ctx.set("content-type", "image/jpeg");
  ctx.set("cache-control", "no-store");
  ctx.body = file;
});

processRouter.post("/run/:dataset", async (ctx) => {
  const { dataset } = ctx.params;
  const { fog, light, noise, scale, geo } = ctx.request.body as {
    fog: string;
    light: string;
    noise: string;
    scale: string;
    geo: string;
  };
  const cmds = [];
  cmds.push("preprocess.py");
  cmds.push("--dataset");
  cmds.push(dataset);
  cmds.push("--light");
  cmds.push(light);
  cmds.push("--fog");
  cmds.push(fog);
  cmds.push("--geo");
  cmds.push(geo);
  cmds.push("--noise");
  cmds.push(noise);
  cmds.push("--scale");
  cmds.push(scale);
  const child = spawnSync("python", cmds, {
    cwd: path.join(process.cwd(), "app"),
  });
  if (child.status !== 0) {
    console.log(child.stderr.toString());
    ctx.body = "failed";
  } else {
    const name = `${dataset}_${new Date().getTime()}`;
    await prisma.dataset.create({
      data: {
        origin: dataset,
        name,
        fog: parseFloat(fog),
        light: parseFloat(light),
        noise: parseFloat(noise),
        geo: parseFloat(geo),
        scale: parseFloat(scale),
      },
    });

    const imagePath = path.join(process.cwd(), "app", "noisy_input");
    const labelPath = path.join(
      process.cwd(),
      "app",
      "dataset",
      dataset,
      "labels"
    );

    const targetPath = path.join(process.cwd(), "app", "dataset", name);
    fs.mkdirSync(path.join(targetPath, "images"), { recursive: true });
    fs.mkdirSync(path.join(targetPath, "labels"), { recursive: true });

    for (let file of fs.readdirSync(imagePath)) {
      fs.copyFileSync(
        path.join(imagePath, file),
        path.join(targetPath, "images", file)
      );
    }
    for (let file of fs.readdirSync(labelPath)) {
      fs.copyFileSync(
        path.join(labelPath, file),
        path.join(targetPath, "labels", file)
      );
    }

    ctx.body = "success";
  }
});

export default processRouter;
